import {
  IButtonContainerState,
  ControlVO,
  Srfuf,
  IGridRowState,
} from '@ibiz-template/runtime';
import { GridController } from './grid.controller';

/**
 * 表格行数据状态管理控制器
 *
 * @author lxm
 * @date 2022-09-05 19:09:02
 * @export
 * @class GridRowState
 */
export class GridRowState implements IGridRowState {
  data: ControlVO;

  /**
   * 错误信息集合，p是对应属性名称
   *
   * @author lxm
   * @date 2022-09-06 15:09:54
   * @type {({ [p: string]: string | null })}
   */
  errors: { [p: string]: string | null } = {};

  /**
   * 操作列状态(p是操作列的标识)
   *
   * @author lxm
   * @date 2022-09-07 22:09:38
   * @type {({ [p: string]: IButtonContainerState })}
   */
  uaColStates: { [p: string]: IButtonContainerState } = {};

  /**
   * 编辑列的状态
   *
   * @author lxm
   * @date 2022-09-20 15:09:58
   * @type {({ [p: string]: { disabled: boolean } })}
   */
  editColStates: {
    [p: string]: {
      disabled: boolean;
      editable: boolean;
      required: boolean;
    };
  } = {};

  /**
   * 是否显示行编辑
   *
   * @author lxm
   * @date 2022-09-05 22:09:23
   * @type {boolean}
   */
  showRowEdit: boolean = false;

  /**
   * 是否被修改过
   *
   * @author lxm
   * @date 2022-11-02 22:11:33
   * @type {boolean}
   */
  modified: boolean = false;

  /**
   * 是否正在处理中(动态控制，值规则，表单项更新等逻辑中)
   * @author lxm
   * @date 2023-03-06 08:00:22
   * @type {boolean}
   * @memberof GridRowState
   */
  processing: boolean = false;

  constructor(data: ControlVO, grid: GridController) {
    this.data = data;

    // vue监控没有空值没法自动响应式更新
    Object.keys(this.data).forEach(key => {
      if (this.errors[key] === undefined) {
        this.errors[key] = null;
      }
    });

    // 新建数据默认开启行编辑
    if (data.srfuf === Srfuf.CREATE) {
      this.showRowEdit = true;
    }

    // 初始化操作列状态
    Object.values(grid.uaColumns).forEach(column => {
      column.initActionStates(this);
    });

    // 初始化编辑项状态
    Object.values(grid.editColumns).forEach(editColumn => {
      this.editColStates[editColumn.fieldName] = {
        disabled: false,
        editable: ibiz.config.grid.editShowMode === 'all',
        required: false,
      };
    });
  }
}
